const fs = require("fs");
const path = require("path");

// 文件是否存在
function isFileExists(filePath) {
  return fs.existsSync(filePath);
}

// 读取文件内容
function readFile(filePath, encoding = "utf-8") {
  if (isFileExists(filePath)) {
    return fs.readFileSync(filePath, { encoding });
  }
  return null;
}

// 写入文件内容
function writeFile(filePath, content, encoding = "utf-8") {
  // 确保目录存在
  const dir = path.dirname(filePath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }

  fs.writeFileSync(filePath, content, { encoding });
  return true;
}

// 获取文件信息
function getFileInfo(filePath) {
  if (isFileExists(filePath)) {
    const stats = fs.statSync(filePath);
    return {
      size: stats.size,
      isFile: stats.isFile(),
      isDirectory: stats.isDirectory(),
      createTime: stats.birthtime,
      modifyTime: stats.mtime,
      accessTime: stats.atime,
    };
  }
  return null;
}

// 读取目录内容
function readDir(dirPath) {
  if (isFileExists(dirPath)) {
    return fs.readdirSync(dirPath);
  }
  return [];
}

// 创建目录
function createDir(dirPath) {
  fs.mkdirSync(dirPath, { recursive: true });
  return true;
}

// 删除文件或目录
function removePath(targetPath) {
  if (isFileExists(targetPath)) {
    const stats = fs.statSync(targetPath);
    if (stats.isDirectory()) {
      fs.rmdirSync(targetPath, { recursive: true });
    } else {
      fs.unlinkSync(targetPath);
    }
    return true;
  }
  return false;
}

// 复制文件或目录
function copyPath(srcPath, destPath) {
  // 确保目标目录存在
  const destDir = path.dirname(destPath);
  if (!fs.existsSync(destDir)) {
    fs.mkdirSync(destDir, { recursive: true });
  }

  fs.cpSync(srcPath, destPath, { recursive: true });
  return true;
}

// 通过路径获取文件或文件夹名称
function getFileName(filePath) {
  return path.basename(filePath);
}

// 路径拼接
function pathJoin(...paths) {
  return path.join(...paths);
}

module.exports = {
  isFileExists,
  readFile,
  writeFile,
  getFileInfo,
  readDir,
  createDir,
  removePath,
  copyPath,
  getFileName,
  pathJoin,
};
